<?php

namespace App\ServicesNew\Impl;

use App\Entities\DistributorEntity;
use App\Entities\OrderEntity;
use App\Entities\TransactionRecordEntity;
use App\Entities\TransactionRecordModel;
use App\ServicesNew\UserBalanceService;
use App\Utils\Assert;
use App\Utils\MoneyFormatUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserBalanceServiceImpl implements UserBalanceService
{
    /**
     * @inheritDoc
     */
    public function getUseAbleAmountByUid(int $userId)
    {
        $distributorEntity = DistributorEntity::findByUserId($userId);

        if (is_null($distributorEntity)) {
            return 0;
        } else {
            return MoneyFormatUtil::dollarToPenny($distributorEntity->getBalance());
        }
    }

    /**
     * @inheritDoc
     */
    public function use(int $userId, int $useAmount)
    {
        $useAmount = MoneyFormatUtil::pennyToDollar($useAmount);
        $distributorEntity = DistributorEntity::findByUserId($userId);
        Assert::notNull($distributorEntity);

        $remainAmount = max(0, $distributorEntity->getBalance() - $useAmount);

        DB::beginTransaction();

        // 1. 修改余额表
        $distributorEntity->setBalance($remainAmount);
        $distributorEntity->save();

        // 2. 记录余额使用记录
        $record = TransactionRecordEntity::getNewInstance();
        $record->setDisId($userId);
        $record->setMoney(-1 * $useAmount);
        $record->setType(TransactionRecordModel::TRANSACTION_RECORD_TYPE_余额抵扣);
        $record->setCreatedAt(Carbon::now()->toDateTimeString());
        $record->save();

        DB::commit();

        return $record->getId();
    }

    /**
     * @inheritDoc
     */
    public function orderRollback(OrderEntity $order)
    {
        $userId = $order->getUserId();
        $transactionRecordId = $order->getTransactionRecordId();

        DB::beginTransaction();

        // 1. 查找对应记录
        $transactionRecord = TransactionRecordEntity::find($transactionRecordId);

        // 2. 新增回退记录
        $transactionRecordNew = TransactionRecordEntity::getNewInstance();
        $transactionRecordNew->setDisId($userId);
        $transactionRecordNew->setMoney($transactionRecord->getMoney() * -1);   // 金额增加
        $transactionRecordNew->setType(TransactionRecordModel::TRANSACTION_RECORD_TYPE_余额回退);
        $transactionRecordNew->save();

        // 3. 修改用户余额
        $distributorEntity = DistributorEntity::findByUserId($userId);
        Assert::notNull($distributorEntity);
        $distributorEntity->setBalance(MoneyFormatUtil::dollarAddDollar($distributorEntity->getBalance(), $transactionRecordNew->getMoney()));
        $distributorEntity->save();

        DB::commit();
        Log::info('回退金额：' . $transactionRecordNew->getMoney() . ' 元');
    }
}
